package com.zone.trigger.listener;

import com.alibaba.fastjson.JSONObject;
import com.zone.domain.common.factory.SimpleFactory;
import com.zone.domain.credit.event.UserCreditAdjustEvent;
import com.zone.domain.credit.service.adjust.IUserCreditAdjustService;
import com.zone.types.event.BaseMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author: zongzi
 * @description: 用户积分变更消费处理器
 * @date: 2025/3/13
 */
@Slf4j
@Component
public class UserCreditAdjustConsumer {

    @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.user_credit_adjust}"))
    public void consumer(BaseMessage<UserCreditAdjustEvent> message) {
        log.info("用户积分变更消费：{}", JSONObject.toJSONString(message));
        UserCreditAdjustEvent userCreditAdjustEvent = message.getData();

        SimpleFactory<IUserCreditAdjustService> creditAdjustSimpleFactory = new SimpleFactory<>(IUserCreditAdjustService.class);
        IUserCreditAdjustService userCreditAdjustService = creditAdjustSimpleFactory.newInstance(userCreditAdjustEvent.getTradeName());
        if (Objects.isNull(userCreditAdjustService)) {
            log.info("未查询到用户积分变更活动处理器，eventMessage = {}", JSONObject.toJSONString(message));
            return;
        }
        try {
            userCreditAdjustService.adjust(userCreditAdjustEvent);
        } catch (Exception e) {
            log.error("用户积分变更处理失败，handlerFactoryName = {} eventMessage = {}", userCreditAdjustEvent.getTradeName(), JSONObject.toJSONString(message), e);
        }
    }

}
